# -*- coding: utf-8 -*-
import sys,os
import time
from django.shortcuts import render_to_response
reload(sys)
sys.setdefaultencoding('utf-8')

from django.http import HttpResponse
import json
from apns import APNs, Payload
import requests
from lxml.html.clean import Cleaner
from lxml.html import fromstring
from requests.compat import urlparse
from readability import Document
import re
from app import models
from app.models import SettingsModel,UserModel
from django.forms.models import model_to_dict  

def users(request):
    _GET = request.GET
    content = ""
    if _GET:
        if _GET.has_key("action"):
            if _GET["action"] == "list":
                for obj in UserModel.objects.all():
                    content +=  json.dumps(model_to_dict(obj),ensure_ascii=False)
            elif _GET["action"] == "updateAllUsers":
                response = requests.get("http://www.codeguesser.cn/server/?action=getUsers")
                content = response.content
                UserModel.vsave(json.loads(content)["data"]["openid"])
                for openid in json.loads(content)["data"]["openid"]:
                    response1 = requests.get("http://www.codeguesser.cn/server/?action=getUser&openid="+openid)
                    UserModel.vupdate(openid,json.loads(response1.content)["nickname"])
                for obj in UserModel.objects.all():
                    content +=  json.dumps(model_to_dict(obj),ensure_ascii=False)
                    
    print content
    return HttpResponse(content)
def setting(request):
    _GET = request.GET
    content = ""
    if _GET:
        if _GET.has_key("action"):
            if _GET["action"] == "list":
                for obj in SettingsModel.objects.all():
                    content +=  json.dumps(model_to_dict(obj),ensure_ascii=False)
            if _GET["action"] == "set":
                
                if _GET["key"] and _GET["value"]:
                    SettingsModel.vset(_GET["key"],_GET["value"])
                    content = "saved"
                else:
                    content = "bad para"
            if _GET["action"] == "get":
                if _GET["key"]:
                    content=SettingsModel.vget(_GET["key"])
    print content
    return HttpResponse(content)
def server(request):
    _GET = request.GET
    url = "http://www.baidu.com"
    dic = {}
    isUseData = False
    if _GET:
        if _GET.has_key("action"):
            access_token = SettingsModel.vget("access_token")
            openid = "osA70wiX37Xxy_luB_95oFOqQSgQ"
            #获取和微信服务器进行交互的token
            if _GET["action"] == "getToken":
                url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1bc33d38d4fcd1e2&secret=a725e5d8904820eb32a28357d2dad756"
            #获取公众号的全部用户列表
            elif _GET["action"] == "getUsers":
                next_openid = ""
                if _GET.has_key("next_openid"):
                    next_openid = _GET["next_openid"]
                url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid
            #获取公众号的某一个联系人的详细信息
            elif _GET["action"] == "getUser":
                if _GET.has_key("openid"):
                    openid = _GET["openid"]
                url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN"
                print url
            #创建公众号里的菜单按钮
            elif _GET["action"] == "createButton":
                url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token
                dic = {"button":[{"name":u"投资管理","sub_button":[{"type":"click","name":u"获取最新的票据","key":"wechat0001"}]},
                                 {"name":u"中投银信","sub_button":[{"type":"view","name":u"关于我们","url":"http://piao88.cc/"}]}
                                 ]
                       }
                dic = json.dumps(dic, ensure_ascii=False).encode('utf-8')
                isUseData = True
            elif _GET["action"] == "deleteButton":
                url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+access_token
                dic = {"button":[{"name":"menu","sub_button":[{"type":"click","name":"test","key":"wechat0001"}]}]}
                
                
        else:
            print json.dumps(_GET,ensure_ascii=False)
            
#     url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=47MXWn2pie08MsDZOe_mNDOO922Oz-MH4ed2M7XCZ_UBLM4MZNu6DsckAcVDPfqT9_vs-MWQcdCbbzpX-2I98xcab36SWoNOHeDiAjNAtmiqEs3MoQmdJIlGS0lL0KM3TCQfAHADMA"
#     dic = {"button":[{"name":"menu","sub_button":[{"type":"click","name":"test","key":"wechat0001"}]}]}
    json1 = json.dumps(dic,ensure_ascii=False)
    print json1
    if isUseData:
        response = requests.post(url,data=dic)
        return HttpResponse(response.content)
    else:
        response = requests.post(url,json=dic)
        return HttpResponse(response.content)
def auth(request):
    _GET = request.GET
    developerOpenid = "gh_7d94543745b2"
    response_data = json.dumps({"errcode":0,"errmsg":"ok"},ensure_ascii=False)
    if _GET:
        #用于认证服务器
        if _GET.has_key("echostr"):
            return HttpResponse(_GET["echostr"])
        else:
        #用于接收用户的消息，
            openid = ""
            nonce = ""
            if _GET.has_key("openid"):
                print "用户的openid："+_GET["openid"]
                openid = _GET["openid"]
            if _GET.has_key("nonce"):
                print "用户的消息类型："+_GET["nonce"]
                nonce = _GET["nonce"]
            u =  UserModel.objects.get(openid=openid)
            content = "你好："+u.nickname
            time1 = "%d" %  time.time()
            response_data = "<xml><ToUserName><![CDATA["+openid+"]]></ToUserName><FromUserName><![CDATA["+developerOpenid+"]]></FromUserName><CreateTime>"+time1+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["+content+"]]></Content></xml>"

            print json.dumps(_GET,ensure_ascii=False)
#             return HttpResponse(json.dumps(_GET,ensure_ascii=False))
    _POST = request.POST
    if _POST:
        print _POST
        return HttpResponse(_POST)
#    encodingAESKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG" 
#    to_xml = """ <xml><ToUserName><![CDATA[oia2TjjewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType>  <![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Descript  ion><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>"""
#    token = "spamtest"
#    nonce = "1320562132"
#    appid = "wx1bc33d38d4fcd1e2"
#    #测试加密接口
#    encryp_test = WXBizMsgCrypt(token,encodingAESKey,appid)
#    ret,encrypt_xml = encryp_test.EncryptMsg(to_xml,nonce)   
#    print ret,encrypt_xml 
#    
# 
#    #测试解密接口
#    timestamp = "1409735669"
#    msg_sign  = "5d197aaffba7e9b25a30732f161a50dee96bd5fa"   
#    
#    from_xml = """<xml><ToUserName><![CDATA[gh_10f6c3c3ac5a]]></ToUserName><FromUserName><![CDATA[oyORnuP8q7ou2gfYjqLzSIWZf0rs]]></FromUserName><CreateTime>1409735668</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[abcdteT]]></Content><MsgId>6054768590064713728</MsgId><Encrypt><![CDATA[hyzAe4OzmOMbd6TvGdIOO6uBmdJoD0Fk53REIHvxYtJlE2B655HuD0m8KUePWB3+LrPXo87wzQ1QLvbeUgmBM4x6F8PGHQHFVAFmOD2LdJF9FrXpbUAh0B5GIItb52sn896wVsMSHGuPE328HnRGBcrS7C41IzDWyWNlZkyyXwon8T332jisa+h6tEDYsVticbSnyU8dKOIbgU6ux5VTjg3yt+WGzjlpKn6NPhRjpA912xMezR4kw6KWwMrCVKSVCZciVGCgavjIQ6X8tCOp3yZbGpy0VxpAe+77TszTfRd5RJSVO/HTnifJpXgCSUdUue1v6h0EIBYYI1BD1DlD+C0CR8e6OewpusjZ4uBl9FyJvnhvQl+q5rv1ixrcpCumEPo5MJSgM9ehVsNPfUM669WuMyVWQLCzpu9GhglF2PE=]]></Encrypt></xml>"""
#    decrypt_test = WXBizMsgCrypt(token,encodingAESKey,appid)
#    ret ,decryp_xml = decrypt_test.DecryptMsg(from_xml, msg_sign, timestamp, nonce)
#    print ret ,decryp_xml
#     return render_to_response('idle.xml',content_type="application/xml")
    return HttpResponse(response_data)
def send(request):
    print request.POST
    return render_to_response('idle.xml',content_type="application/xml")

def notification(request):
    
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    apns = APNs(use_sandbox=True, cert_file=BASE_DIR+'/cert.pem', key_file=BASE_DIR+'/key.pem')
    token_hex = '32ee922e88e39c9652e884f43f17c9dc80cf26ccbbb06827e8ae05577e55ab8f'
    payload = Payload(alert="道友，你在干嘛？", sound="default", badge=1)
    apns.gateway_server.send_notification(token_hex, payload)
    return HttpResponse('data')

def index(request):
#     response = requests.get('http://www.17k.com/chapter/2397656/27979850.html')
#     doc = Document(response.text)
#     content = doc.content()
    dic = {"success":"true","code":"0","msg":"","result":[{"id":0,"name":"渔港春夜","url":'http://www.yugangchunye.com/default1.html'},{"id":1,"name":"魔法学徒","url":'https://www.shukeba.com/161201/'},{"id":2,"name":"幻刃仙缘","url":'https://www.vipxs.la/56_56959/'}]}
    data = json.dumps(dic,ensure_ascii=False)
    return HttpResponse(data)

def chapter(request):
    bookidIndex = request.GET['bookidIndex']
    bookid = request.GET['id']
    headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4'}
    response = requests.get(bookid,headers = headers)
#     doc = Document(response.content.decode('GB18030'))
    originString = response.content
    decodedString = originString
    try:
        decodedString = originString.decode('GB18030')
    except Exception,e:
        print e
    doc = Document(decodedString)
    
    summary = doc.content()
#    print summary
    el = fromstring(summary)
    result = urlparse(response.request.url)
    prefix = result.scheme+"://"+result.hostname
    chapters = []
    titles = []
    index = 0
    for e in el.findall(".//a"):
#        print e.text_content()
        text = e.text_content()
        if re.compile(u"第.*[章|节|部分]").search(text):
            ttttext = re.findall(u"第(.+?)[章|节|部分]", text)[0]
            tempNumber = ttttext.replace(u"一",u"1").replace(u"二",u"2").replace(u"两",u"2").replace(u"三",u"3").replace(u"四",u"4").replace(u"五",u"5").replace(u"六",u"6").replace(u"七",u"7").replace(u"八",u"8").replace(u"九",u"9").replace(u"零",u"0")
            if tempNumber == "十":
                tempNumber = 10
            elif re.compile(u"^十.*").search(tempNumber):
                tempNumber = tempNumber.replace(u"十",u"1")
            elif re.compile(u".*十$").search(tempNumber):
                tempNumber = tempNumber.replace(u"十",u"0")
            else:
                tempNumber = tempNumber.replace(u"十",u"")
                
            if isinstance(tempNumber, int) == False:
                if re.compile(u".*百$").search(tempNumber):
                    tempNumber = tempNumber.replace(u"百",u"00")
                else:
                    tempNumber = tempNumber.replace(u"百",u"")
                    
#             if isinstance(tempNumber, int) == False:
#                 if re.compile(u"第一章").search(text):
#                     index = 0
            if index >= 0:
                if re.compile(u"^/.*").search(e.get("href")):
                    chapters.append({"id":index,"bid":bookidIndex,"title":text,"text":"","url":prefix+e.get("href")})
                elif re.compile(u"^http.*").search(e.get("href")):
                    chapters.append({"id":index,"bid":bookidIndex,"title":text,"text":"","url":e.get("href")})
                else:
                    chapters.append({"id":index,"bid":bookidIndex,"title":text,"text":"","url":bookid+e.get("href")})
                titles.append(text)
                index+=1
    data = json.dumps({"success":"true","code":"0","msg":"","result":chapters},ensure_ascii=False)
    return HttpResponse(data)

def testTimes(el,t):
    parents = []
    times = []
    for e in el.findall(".//a"):
        text = e.text_content()
        if re.compile(u"第.*[章|节|部分]").search(text):
            p_content_text = deepParent(e, t).text_content()
            if p_content_text in parents:
                index = parents.index(p_content_text)
                times[index]= times[index] + 1
            else:
                parents.append(p_content_text)
                times.append(1)
    print parents
    print times
    if 2 in times:
        return True
    else:
        return False
def deepParent(el,t):
    if t==0:
        return el
    else:
        return deepParent(el.getparent(), t-1)
def content(request):
    chapterId = request.GET['id']
    headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4'}
    response = requests.get(chapterId,headers = headers)
    
    originString = response.content
    decodedString = originString
    try:
        decodedString = originString.decode('GB18030')
    except Exception,e:
        print e
    doc = Document(decodedString)
    
    summary = doc.summary()
    d1 = filter_tags(summary)
    data = json.dumps({"success":"true","code":"0","msg":"","result":d1},ensure_ascii=False)
    return HttpResponse(data)

def filter_tags(htmlstr):
#先过滤CDATA
    re_br=re.compile('<br\s*?/?>')#处理换行
    re_p=re.compile('<p\s*?/?>')#处理换行
    re_h=re.compile('</?\w+[^>]*>')#HTML标签
    re_comment=re.compile('<!--[^>]*-->')#HTML注释
    s=re_br.sub('\n',htmlstr)#将br转换为换行
    s=re_p.sub('\n',s)#将br转换为换行
    s=re_h.sub('',s) #去掉HTML 标签
    s=re_comment.sub('',s)#去掉HTML注释
    s=replaceCharEntity(s)#替换实体
    #去掉多余的空行
    blank_line=re.compile('[\n|\t]+')
    s=blank_line.sub('\n',s)
    return s
def replaceCharEntity(htmlstr):
    return htmlstr.replace("&nbsp;"," ").replace("&#160;"," ").replace("&lt;","<").replace("&#60;","<").replace("&gt;",">").replace("&#62;",">").replace("&amp;","&").replace("&#38;","&").replace("&quot;",'"').replace("&#34;",'"').replace("&#13;",'"').replace('\"\n','\n')
def findTargetClass(content):
    return

def addBook(request):
    bookurl = request.GET['id'].decode('ascii').encode('utf-8')
    name = request.GET['name'].decode('ascii').encode('utf-8')
    realId = request.GET['realId'].decode('ascii').encode('utf-8')
    dic = {"success":"true","code":"0","msg":"","result":[{"id":0,"name":"这是第一本书","url":'http://www.biqugetw.com/9_9990/'},{"id":1,"name":"这是第二本书","url":'http://www.biqugetw.com/9_9990/'},{"id":2,"name":"这是第三本书","url":'http://www.biqugetw.com/9_9990/'},{"id":realId,"name":name,"url":bookurl}]}
    data = json.dumps(dic,ensure_ascii=False)
    return HttpResponse(data)
